<?php
/**
 * 悬赏模型类
 */

class RewardModel extends Model
{
    private $reward_id;

    const REWARDING = 0;//悬赏中
    const ADOPTED = 1;//已采纳答案
    const NOT_ADOPTED = 3;//未采纳答案
    const REFUNDING = 2;//退款中
    const REFUNDED = 4;//已退款

    /**
     * 构造函数
     * @author 姜伟
     * @todo 构造函数
     */
    public function __construct($reward_id=0)
    {
        parent::__construct();
        $this->reward_id = $reward_id;
    }  



    public function addReward($arr){
        if(!is_array($arr)) return false;
        $arr['addtime'] = time();
        $r = $this->add($arr);
        if($r){

            


            D('Account')->addAccount($arr['user_id'], AccountModel::POST_REWARD, -$arr['reward_money'], '发布悬赏-'.$arr['post_id'], $r, $arr['post_id']);
            //推消息给邀请的人
            if($arr['invite_users']){
                $link = '/FrontChannel/post_detail/post_id/'.$arr['post_id'];
                $at_title = '在悬赏帖中@了你';
                $reward_user = M('Users')->where('user_id ='.$arr['user_id'])->getField('nickname');
                D('Message')->addMessage($r, MessageModel::AT, $arr['user_id'],  $arr['invite_users'], $reward_user.$at_title, $at_title, $link);
            }
            
        }

        return $r;
    }

    public function getRewardInfo($where){
        return $this->where($where)->find();
    }

    public function getRewardNum($where){
        return $this->where($where)->count();
    }


    public function getRewardList($field =null,$where, $order='addtime desc'){

        return $this->field($field)->where($where)->order($order)->limit()->select();
    }

    public function getListData($reward_list){
        foreach ($reward_list as $k => $v) {
            //帖子信息
            $post_obj = new PostModel();
            $post_info = $post_obj->getPostInfo('post_id ='.$v['post_id']);
            $reward_list[$k]['title'] = $post_info['title'];
            //wangtao 2017.9.15 -strat
            $reward_list[$k]['is_featured'] = $post_info['is_featured'];
            //wangtao 2017.9.15 -end

            //频道名称．
            $channel_obj = new ChannelModel();
            $reward_list[$k]['channel_name'] = $channel_obj->getChannelField($post_info['channel_id'],'channel_name');
            //发布人
            $user = M('Users')->where('user_id ='.$v['user_id'])->find();
            $reward_list[$k]['nick_name'] = $user['nickname'];
            //时间
            $reward_list[$k]['acp_time'] = date('Y-m-d H:i:s', $v['addtime']);
            $reward_list[$k]['acp_end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            //被采纳的用户
            $adopted_user = M('Users')->where('user_id ='.$v['adopted_user'])->find();
            $reward_list[$k]['adopted_name'] = $adopted_user['nickname'];
            //退款原因
            $reward_refund_reason_obj = new RewardRefundReasonModel();
            $reward_refund_reason_info = $reward_refund_reason_obj->getRewardRefundReasonInfo('reward_refund_reason_id ='.$v['refund_reason_id']);
            $reward_list[$k]['refund_reason'] = $reward_refund_reason_info['reason'];

            //状态
            $url = '';//详情连接
            $url_answer = '';
            $url_comment_list = '';
            if ($v['status'] == self::REWARDING) {
                $url = 'get_rewarding_detail';
                $url_answer = 'get_rewarding_answer_list';
                $url_comment_list = 'get_rewarding_comment_list';

            }elseif ($v['status'] == self::ADOPTED){
                $url = 'get_adopted_detail';
                $url_answer = 'get_adopted_answer_list';
                $url_comment_list = 'get_adopted_comment_list';

            }elseif ($v['status'] == self::NOT_ADOPTED){
                $url = 'get_not_adopted_detail';
                $url_answer = 'get_not_adopted_answer_list';
                $url_comment_list = 'get_not_adopted_comment_list';

            }elseif ($v['status'] == self::REFUNDING){
                $url = 'get_refunding_detail';
                $url_answer = 'get_refunding_answer_list';
                $url_comment_list = 'get_refunding_comment_list';

            }elseif ($v['status'] == self::REFUNDED){
                $url = 'get_refunded_detail';
                $url_answer = 'get_refunded_answer_list';
                $url_comment_list = 'get_refunded_comment_list';
            }

            if($v['is_del']){
                $url = 'get_del_reward_detail';
                $url_answer = 'get_del_answer_list';
                $url_comment_list = 'get_del_reward_comment_list';
            }

            $reward_list[$k]['url_detail'] = $url;
            $reward_list[$k]['url_answer'] = $url_answer;
            $reward_list[$k]['url_comment_list'] = $url_comment_list;

        }
        return $reward_list;
    }


    //采纳答案
    public function cainaAnswer($reward_id, $answer_id){
        $reward = $this->getRewardInfo('reward_id ='.$reward_id);
        $answer_obj = new RewardAnswerModel();
        $answer = $answer_obj->getRewardAnswerInfo('reward_answer_id ='.$answer_id);

        $arr = array(
            'answer_id' => $answer_id,
            'adopted_user' => $answer['user_id'],
            'status' => self::ADOPTED,
            );
        $r = $this->where('reward_id ='.$reward_id)->save($arr);
        if($r){

            $answer_obj->where('reward_answer_id ='.$answer_id)->save(array('is_adopt'=>1));


            //wangtao 2017.9.15 -start
            //采纳成功将悬赏金给回答的人
            $money = $this->getRewarMoney($answer['user_id'],$reward['post_id']);
            $money = round($reward['reward_money'] * $money / 100,2);
            $reward['reward_money'] = $reward['reward_money'] - $money;
            //wangtao 2017.9.15 -end
            D('Post')->setPost($arr['post_id'],array( 'updatetime' => time()));
            D('Account')->addAccount($answer['user_id'], AccountModel::REWARD_SUCCESS, $reward['reward_money'], '悬赏奖金-'.$reward['post_id'], $reward_id);
        }

        return $r;
    }

    //修改退款申请后的状态
    public function setStatus($reward_id,$state){
        return $this->where('reward_id ='.$reward_id)->save(array('status' => $state));
    }

    //申请退款
    public function rewardRefund($reward_id, $reason_id){
        $arr = array(
            'status' => self::REFUNDING,
            'refund_reason_id' => $reason_id,
            );
        return $this->where('reward_id ='.$reward_id)->save($arr);
    }

    //同意 or 拒绝
    public function rewardIsRefunded($reward_id,$type){
        $reward_info =self::getRewardInfo('reward_id ='.$reward_id);
        $account_obj = new AccountModel();
        $success = 0;
        if($type == self::REFUNDED){ //同意
            $success = $account_obj->addAccount($reward_info['user_id'],AccountModel::REWARD_REFUND,$reward_info['reward_money'],'悬赏退款',$reward_id,$reward_info['post_id']);
            
            if($success){
                $content = '您的悬赏贴《'.D('Post')->getTitleById($reward_info['post_id']).'》退款申请已通过，悬赏金将退回到余额中';
                D('Message')->addMessage($reward_info['post_id'], MessageModel::REWARD, 0, $reward_info['user_id'], $content, $content);
                $success = self::setStatus($reward_id,$type);
            }
        }

        if($type == self::NOT_ADOPTED){ //拒绝退款
            if(time() >= $reward_info['end_time'] ){ //操作时间大于结束时间,则平分．
                $reward_answer_obj = new RewardAnswerModel();
                $answer_num = $reward_answer_obj->getRewardAnswerNumByReward($reward_id);
                $average_money = round($reward_info['reward_money'] / $answer_num,2);

                $reward_answer_list = $reward_answer_obj->getRewardAnswerAllList('','reward_id ='.$reward_id);
                D('Post')->setPost($reward_info['post_id'],array( 'updatetime' => time()));
                $content = '您参加的悬赏贴《'.D('Post')->getTitleById($reward_info['post_id']).'》由于楼主未采纳答案，您将获得¥';
                foreach($reward_answer_list as $k => $v){
                    //wangtao 2017.9.15 -start
                    //据用户的ID或帖子频道获取分成
                    $money = $this->getRewarMoney($v['user_id'],$reward_info['post_id']);
                    $money = round($average_money * $money / 100,2);
                    $average_money = $average_money - $money;
                    //wangtao 2017.9.15 -end

                    $content .= $average_money.'悬赏奖金';
                    $success += $account_obj->addAccount($v['user_id'],AccountModel::REWARD_REJECT,$average_money,'退款拒绝，答题者平分金额',$reward_id,$reward_info['post_id']);
                    if($success){
                         D('Message')->addMessage($reward_info['post_id'], MessageModel::REWARD, 0, $v['user_id'], $content, $content);
                    }
                }
                if($success){

                    $success = self::setStatus($reward_id,$type);
                }
            }else{ //操作时间小于结束时间,则继续悬赏．

                $success =  self::setStatus($reward_id,self::REWARDING);
                $content = '您的悬赏贴《'.D('Post')->getTitleById($reward_info['post_id']).'》的退款申请已被拒绝';
                D('Message')->addMessage($reward_info['post_id'], MessageModel::REWARD, 0, $reward_info['user_id'], $content, $content);
            }
        }

        return $success;
    }
    //查询某个字段
    public function getRewardField($where,$field){
        return $this->where($where)->getField($field);
    }

    public function getRewardFields($where,$field,$group=''){
        return $this->where($where)->group($group)->getField($field,true);
    }

    //wangtao 2017.9.15 -start
    /**
     * 根据用户的ID和当前帖子的ID来获取分成
     * @param $user_id 根据用户的ID
     * @param $post_id 当前帖子的ID
     * @return int
     */
    public function getRewarMoney($user_id,$post_id){
        //根据用户的头衔来扣除分成
        $money = D('UserTitle')->getTitlePostCash($user_id);
        if($money){
            //根据用户的头衔来扣除分成
            $money = intval($money[0]['title_rates']);
        }else{
            //根据当前频道来扣除分成
            $money = D('Post')->getPostReatts($post_id)[0]['channel_rates'];
        }
        return $money;
    }

    //wangtao 2017.9.15 -end

    //平分悬赏金
    public function avgRewardMoney($reward_id){
        $reward_info =self::getRewardInfo('reward_id ='.$reward_id);
        $reward_answer_obj = new RewardAnswerModel();
        $answer_num = $reward_answer_obj->getRewardAnswerNumByReward($reward_id);
        $average_money = round($reward_info['reward_money'] / $answer_num,2);
        $reward_answer_list = $reward_answer_obj->getRewardAnswerAllList('','reward_id ='.$reward_id);
        $num = 0;
        if(count($reward_answer_list) > 0){

            D('Post')->setPost($reward_info['post_id'],array( 'updatetime' => time()));
            $content = '您参加的悬赏贴《'.D('Post')->getTitleById($reward_info['post_id']).'》由于楼主未采纳答案，您将获得¥';
            foreach($reward_answer_list as $k => $v){

                //wangtao 2017.9.15 -start
                //据用户的ID或帖子频道获取分成
                $money = $this->getRewarMoney($v['user_id'],$reward_info['post_id']);
                $money = round($average_money * $money / 100,2);
                $average_money = $average_money - $money;
                $content .=$average_money.'悬赏奖金';
                //wangtao 2017.9.15 -end
                $num += D('Account')->addAccount($v['user_id'],AccountModel::REWARD_REJECT,$average_money,'答题者平分金额',$reward_id,$reward_info['post_id']);

                D('Message')->addMessage($reward_info['post_id'], MessageModel::REWARD, 0, $v['user_id'], $content, $content);
                
            }
            if($num){
                $success = self::setStatus($reward_id, self::NOT_ADOPTED);
                return $success;
            }
        }else{
            //没有答案直接退款
            $success = D('Account')->addAccount($reward_info['user_id'],AccountModel::REWARD_REFUND,$reward_info['reward_money'],'悬赏退款',$reward_id,$reward_info['post_id']);
            if($success){
                $success = self::setStatus($reward_id,self::REFUNDED);
                $content = '您的悬赏贴《'.D('Post')->getTitleById($reward_info['post_id']).'》由于无人回答，悬赏金将退回到余额中';
                D('Message')->addMessage($reward_info['post_id'], MessageModel::REWARD, 0, $reward_info['user_id'], $content, $content);
                return $success;
            }
        }
        
        return false;
    }


    //悬赏未采纳答案
    public function noAdoptAvgRewardMoney(){
        $where = 'status ='.self::REWARDING . ' and end_time <='.time();
        $reward_ids = $this->where($where)->getField('reward_id', true);
        log_file('no_adopt_reward ='.json_encode($reward_ids), 'no_adopt_reward');
        foreach ($reward_ids as $k => $v) {
            $this->avgRewardMoney($v);
        }
    }

    public function delPost($post_id){
        return $this->where('post_id ='.$post_id)->save(array('is_del' => 1));
    }
}
